// ml:run = $bin < input
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>

std::ifstream fin{"generators.in"};
std::ofstream fout{"generators.out"};

using ll = long long;
int const inf = 1 << 28;

struct data { int pos, x; };
bool operator<(data const& a, data const& b)
{
    return a.x < b.x;
}

std::vector<std::vector<data>> da;
std::vector<int> pre;
ll n, k;

int tmp[2000];

int main()
{
    std::ios_base::sync_with_stdio(false);
    fin >> n >> k;
    da.resize(n);
    pre.resize(n);
    ll sum = 0;
    for (int i = 0; i < n; i++) {
        int x0, a, b, c;
        fin >> x0 >> a >> b >> c;
        for (int j = 0; j < c; j++) tmp[j] = -1;
        tmp[x0] = 0;
        for (int j = 1; ; j++) {
            x0 = (a * x0 + b) % c;
            if (tmp[x0] != -1) break;
            tmp[x0] = j;
        }
        for (int j = 0; j < c; j++) {
            if (tmp[j] == -1) continue;
            da[i].push_back({tmp[j], j});
        }
        sum += da[i][da[i].size() - 1].x;
    }
    if (sum % k != 0) {
        fout << sum << "\n";
        for (int i = 0; i < n; i++)
            fout << da[i][da[i].size() - 1].pos << " ";
        fout << "\n";
    } else {
        ll min = inf;
        int pos = -1, pos2 = -1;
        for (int i = 0; i < n; i++) {
            for (int j = da[i].size() - 2; j >= 0; j--) {
                int d = da[i][da[i].size() - 1].x - da[i][j].x;
                if ((d % k) && d < min) {
                    min = d;
                    pos = i; pos2 = j;
                    break;
                }
            }
        }
        if (pos != -1) {
            sum -= min;
            fout << sum << "\n";
            for (int j = 0; j < n; j++) {
                if (j != pos) fout << da[j][da[j].size() - 1].pos << " ";
                else fout << da[j][pos2].pos << " ";
            }
        } else
            fout << "-1\n";
    }
}

